/*
 * @lc app=leetcode.cn id=445 lang=cpp
 *
 * [445] 两数相加 II
 */
#include "include.h"

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    // reverse operation => stack ~~~
    
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* reversedNum1 = reverseList(l1);
        ListNode* reversedNum2 = reverseList(l2);
        ;
        ListNode* result = nullptr;

        bool overFlow;
        while (reversedNum1 or reversedNum2 or overFlow){
            int num = 0;
            if (reversedNum1){
                num += reversedNum1->val;
                reversedNum1 = reversedNum1->next;
            }
            if (reversedNum2){
                num += reversedNum2->val;
                reversedNum2 = reversedNum2->next;
            }
            if (overFlow){
                num += 1;
            }
            if (num >= 10){
                overFlow = true;
                num -= 10;
            } else{
                overFlow = false;
            }
            ListNode* newBit = new ListNode(num);
            newBit->next = result;
            result = newBit;
        }
        return result;
    }
    ListNode* reverseList(ListNode* head){
        // if (head == nullptr){return;}
        ListNode* prev = nullptr;
        ListNode* current = head;
        
        // ListNode* last; // = head
        while (current){
            ListNode* next = current->next;
            current->next = prev;
            prev = current;
            current = next;
        }

        return prev;
    }
};
// @lc code=end

